package com.dbappsecurity.bifrost.base;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import butterknife.Unbinder;
import com.dbappsecurity.bifrost.BifrostApp;
import com.dbappsecurity.bifrost.contract.BaseContract;
import com.dbappsecurity.bifrost.di.component.DaggerFragmentComponent;
import com.dbappsecurity.bifrost.di.component.FragmentComponent;
import com.dbappsecurity.bifrost.di.module.FragmentModule;
import com.dbappsecurity.core.CoreBaseFragment;
import com.dbappsecurity.network.Thunder;
import com.tbruyelle.rxpermissions2.RxPermissions;
import dagger.Lazy;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import javax.inject.Inject;

public abstract class InjectBaseFragment extends CoreBaseFragment implements BaseContract.View {
  protected FragmentComponent mFragmentComponent;

  @Inject protected Lazy<Thunder> mApiClient;

  @Inject protected Unbinder mUnBinder;

  @Inject protected Lazy<CompositeDisposable> mDisposables;

  @Inject protected Lazy<RxPermissions> permissions;

  @Override
  public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mFragmentComponent = DaggerFragmentComponent.builder()
        .app(BifrostApp.sAppComponent)
        .base(new FragmentModule(this))
        .setContractView(this)
        .setRootView(view)
        .build();

    mFragmentComponent.inject(this);
  }

  @Override
  public void onDestroyView() {
    super.onDestroyView();
    if (mUnBinder != null) mUnBinder.unbind();
    if (mDisposables != null) mDisposables.get().clear();
    mFragmentComponent = null;
  }

  protected void addDisposable(Disposable disposable) {
    if (mDisposables != null) mDisposables.get().add(disposable);
  }

  protected void removeDisposable(Disposable disposable) {
    if (mDisposables != null) {
      mDisposables.get().remove(disposable);
    }
  }
}
